/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jifIngresarRequerimiento.java
 *
 * Created on 03/06/2010, 09:15:39 AM
 */

package Requerrimientos;

import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.Listas;
import administracion.helper.MiTablePrint;
import administracion.helper.Utiles_MensajesDialogo;
import administracion.helper.Utiles_Tabla;
import administracion.propiedades.Propiedades;
import com.jidesoft.hints.ListDataIntelliHints;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.beansbinding.ELProperty;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;
import suministros.ejb30.TO.CentroCostoTO;
import suministros.ejb30.TO.EmpresaTO;
import suministros.ejb30.TO.NecesidadesSumiDetalleTO;
import suministros.ejb30.TO.NecesidadesSumiTO;
import suministros.ejb30.TO.ProyectoTO;
import suministros.ejb30.TO.SuministroTO;
import suministros.ejb30.TO.UnidadOrganizativaTO;
import suministros.ejb30.TO.ZonaTO;
import suministros.ejb30.entity.CentroCosto;
import suministros.ejb30.entity.Parametros;
import suministros.ejb30.entity.Proyecto;
import suministros.ejb30.entity.UnidadOrganizativa;
import suministros.ejb30.helper.Utiles_Convertir;

/**
 *
 * @author Diana
 */
public class jifAdministrarRequerimientos extends javax.swing.JInternalFrame {
    private UnidadOrganizativa unid_org_pedido;
    private CentroCosto centro_costos_pedido;
    private Proyecto proyecto_pedido;
    private ListDataIntelliHints intelliHintsUnidOrganica;
    private ListDataIntelliHints intelliHintsCentroCostos;
    private ListDataIntelliHints intelliHintsProyectos;
    private List<NecesidadesSumiTO> requerimientos,tareasRequerimientos=new ArrayList(1);
    private List<NecesidadesSumiTO> requerimientosApro= new ArrayList<NecesidadesSumiTO>();
    private List<NecesidadesSumiDetalleTO> detalleRequerimientos;
    private JTableBinding jTableBinding;
    boolean modificable;
    List<EmpresaTO> empresas;
    List<ZonaTO> zonas;
    /** Creates new form jifIngresarRequerimiento */
    public jifAdministrarRequerimientos(boolean modificable) {
        /*try {
            if (GestionPedidosDelegate.getInstance().verificarFechasAprobarRequerrimientos()) {
                initComponents();
                empresas = Listas.getEmpresas();
                if(empresas.isEmpty()){
                    this.jCheckBox1.setEnabled(false);
                }
                this.modificable = modificable;
                this.jbAceptar.setVisible(true);
                this.jCheckBox1.setSelected(false);
                this.llenarComboEmpresa();
                if (this.jchkInversion.isSelected()) {
                    this.jpOperativo.setVisible(false);
                    this.jpInversion.setVisible(true);
                } else {
                    this.jpOperativo.setVisible(true);
                    this.jpInversion.setVisible(false);
                }
                cargaHintsIndependientes();
                this.jcbEmpresa.setEnabled(false);
            } else {
                Utiles_MensajesDialogo.mensajeAlerta("No ha llegado la fecha para administrar los requerrimientos");
            }
        } catch (Exception ex) {
             Utiles_MensajesDialogo.mensajeAlerta("No se ha podido establecer conexion con el servidor");
        }*/
        initComponents();
                empresas = Listas.getEmpresas();
                if(empresas.isEmpty()){
                    this.jCheckBox1.setEnabled(false);
                }
                this.modificable = modificable;
                this.jbAceptar.setVisible(true);
                this.jCheckBox1.setSelected(false);
                this.llenarComboEmpresa();
                if (this.jchkInversion.isSelected()) {
                    this.jpOperativo.setVisible(false);
                    this.jpInversion.setVisible(true);
                } else {
                    this.jpOperativo.setVisible(true);
                    this.jpInversion.setVisible(false);
                }
                cargaHintsIndependientes();
                this.jcbEmpresa.setEnabled(false);
                this.jcbZona.setEnabled(false);
                this.llenarComboZonas();
        
    }
 public Boolean evaluarReq(){
      Boolean estado=false;
      Parametros param;
        try {
            param = Listas.getParametrosID("SU5");
            Date fecha = param.getFecha();
            SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
            String fechaSistema=dateFormat.format(fecha);
            String fechaActual=dateFormat.format(new Date());
            if(fechaSistema.compareTo(fechaActual)<0){
                estado=true;
            }
        } catch (Exception ex) {
            Logger.getLogger(jifEvaluarRequerimiento.class.getName()).log(Level.SEVERE, null, ex);
        }

        return estado;

    }

    private void cargaHintsIndependientes() {
        this.intelliHintsUnidOrganica = new ListDataIntelliHints(this.jtfDesUnOrganica, Listas.getUn_organizativa());
         this.intelliHintsProyectos= new ListDataIntelliHints(this.jtfDesProyecto,Listas.obtenerProyectosPorEmpresa(((EmpresaTO)this.jcbEmpresa.getSelectedItem()).getRuc()));
  }
   private void llenarComboZonas() {
        zonas = null;
        List listaPaises_cbo = this.cboBeanBindingZona1.getLista();
        listaPaises_cbo.clear();
        try
        {
          zonas = Listas.getZonas();
          this.cboBeanBindingZona1.setLista(zonas);
          this.bindingGroup.bind();
          this.jcbZona.updateUI();
          this.jcbZona.setSelectedIndex(0);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener zonas\n" + ex.getMessage());
          ex.printStackTrace();
          Logger.getLogger(jifRegistrarPrecioRequerrimientos.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
   private void llenarComboEmpresa() {
        empresas = null;
        List listaPaises_cbo = this.cboBeanBindingEmpresa1.getLista();
        listaPaises_cbo.clear();
        try
        {
           if(this.jCheckBox1.isSelected()){
                empresas = Listas.getEmpresas();
            }
            else{
                empresas = Listas.getEmpresaPrincipal();
            }
          this.cboBeanBindingEmpresa1.setLista(empresas);
          this.bindingGroup.bind();
          this.jcbEmpresa.updateUI();
          this.jcbEmpresa.setSelectedIndex(0);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener empresas\n" + ex.getMessage());
          ex.printStackTrace();
          Logger.getLogger(jifAdministrarRequerimientos.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    public void verificarAprobacionDependencias(){
       String mensaje="La unidad organizativa no ha sido aprobada por las \n" +
               "siguientes unidades dependientes";
       Boolean estado=false;
       List<UnidadOrganizativaTO> listadependencias= new ArrayList<UnidadOrganizativaTO>();
       String unidad= this.jtfCodUnorganica.getText();
        try {
            listadependencias = GestionPedidosDelegate.getInstance().verificarAprobacionDependencias(unidad);
        } catch (Exception ex) {
            Logger.getLogger(jifEvaluarRequerimiento.class.getName()).log(Level.SEVERE, null, ex);
        }
       for(UnidadOrganizativaTO unidad_depen:listadependencias){
           if(!unidad_depen.isEstado_aprobacion()){
               mensaje=mensaje+"\n "+unidad_depen.getCod_Uni_Organizativa()+" - "+unidad_depen.getUnidad_organizativa();
               estado=true;

           }
       }
       if(estado){
           Utiles_MensajesDialogo.mensajeInfo(mensaje);
       }
       else{
           llenaTablaRequerimientos();
       }

   }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        cboBeanBindingEmpresa1 = new administracion.BeanBinding.CboBeanBindingEmpresa();
        cboBeanBindingZona1 = new administracion.BeanBinding.CboBeanBindingZona();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtRequerimientos = new javax.swing.JTable();
        this.jtRequerimientos.getTableHeader().setReorderingAllowed(false) ;
        jbAceptar = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();
        jpOperativo = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jtfCodUnorganica = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jtfDesUnOrganica = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jtfCodCenCostos = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jtfDescCenCostos = new javax.swing.JTextField();
        jchkInversion = new javax.swing.JCheckBox();
        jpInversion = new javax.swing.JPanel();
        jLabel9 = new javax.swing.JLabel();
        jtfCodProyecto = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jtfDesProyecto = new javax.swing.JTextField();
        jcbEmpresa = new javax.swing.JComboBox();
        jbtImprimir1 = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();
        jcbZona = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setIconifiable(true);
        setTitle("ADMINISTRAR REQUERRIMIENTOS");
        setFrameIcon(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CUADRO DE REQUERIMIENTOS ANUALES", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12), java.awt.Color.blue)); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jtRequerimientos.setFont(new java.awt.Font("Arial", 0, 12));
        jtRequerimientos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID SUMINISTRO", "SUMINISTRO", "UNID.MEDIDA", "SUB TOTAL", "CANTIDAD APROBADA"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Double.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jtRequerimientos.setName("jtRequerimientos"); // NOI18N
        jtRequerimientos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jtRequerimientos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtRequerimientosKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jtRequerimientos);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 743, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
        );

        jbAceptar.setFont(new java.awt.Font("Arial", 0, 12));
        jbAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_ok.png"))); // NOI18N
        jbAceptar.setMnemonic('A');
        jbAceptar.setText("ACEPTAR");
        jbAceptar.setEnabled(false);
        jbAceptar.setName("jbAceptar"); // NOI18N
        jbAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAceptarActionPerformed(evt);
            }
        });

        jbCancelar.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbCancelar.setMnemonic('C');
        jbCancelar.setText("CERRAR");
        jbCancelar.setName("jbCancelar"); // NOI18N
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });

        jpOperativo.setName("jpOperativo"); // NOI18N

        jLabel5.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel5.setText("COD.UN.ORGAN.");
        jLabel5.setName("jLabel5"); // NOI18N

        jtfCodUnorganica.setToolTipText("Codigo de la unidad organica");
        jtfCodUnorganica.setName("jtfCodUnorganica"); // NOI18N
        jtfCodUnorganica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfCodUnorganicaActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel6.setText("DESC.UN.ORGAN.");
        jLabel6.setName("jLabel6"); // NOI18N

        jtfDesUnOrganica.setName("jtfDesUnOrganica"); // NOI18N
        jtfDesUnOrganica.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfDesUnOrganicaActionPerformed(evt);
            }
        });
        jtfDesUnOrganica.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfDesUnOrganicaKeyPressed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel7.setText("COD.CEN.COSTOS");
        jLabel7.setName("jLabel7"); // NOI18N

        jtfCodCenCostos.setFont(new java.awt.Font("Arial 12 Simple", 0, 12));
        jtfCodCenCostos.setName("jtfCodCenCostos"); // NOI18N
        jtfCodCenCostos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfCodCenCostosActionPerformed(evt);
            }
        });

        jLabel8.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel8.setText("DESC.CEN.COSTOS");
        jLabel8.setName("jLabel8"); // NOI18N

        jtfDescCenCostos.setFont(new java.awt.Font("Arial 12 Simple", 0, 12));
        jtfDescCenCostos.setName("jtfDescCenCostos"); // NOI18N
        jtfDescCenCostos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfDescCenCostosActionPerformed(evt);
            }
        });
        jtfDescCenCostos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfDescCenCostosKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jpOperativoLayout = new javax.swing.GroupLayout(jpOperativo);
        jpOperativo.setLayout(jpOperativoLayout);
        jpOperativoLayout.setHorizontalGroup(
            jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7))
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(jtfCodUnorganica, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpOperativoLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jtfCodCenCostos, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jtfDescCenCostos)
                    .addComponent(jtfDesUnOrganica, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpOperativoLayout.setVerticalGroup(
            jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpOperativoLayout.createSequentialGroup()
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jtfCodUnorganica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jtfDesUnOrganica, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpOperativoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jtfCodCenCostos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8)
                    .addComponent(jtfDescCenCostos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jchkInversion.setFont(new java.awt.Font("Arial", 1, 12));
        jchkInversion.setText("DE INVERSION");
        jchkInversion.setName("jchkInversion"); // NOI18N
        jchkInversion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jchkInversionActionPerformed(evt);
            }
        });

        jpInversion.setName("jpInversion"); // NOI18N

        jLabel9.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel9.setText("COD.PROYECTO");
        jLabel9.setName("jLabel9"); // NOI18N

        jtfCodProyecto.setToolTipText("Codigo de la unidad organica");
        jtfCodProyecto.setName("jtfCodProyecto"); // NOI18N
        jtfCodProyecto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfCodProyectoActionPerformed(evt);
            }
        });

        jLabel10.setFont(new java.awt.Font("Arial", 1, 12));
        jLabel10.setText("DESC.PROYECTO");
        jLabel10.setName("jLabel10"); // NOI18N

        jtfDesProyecto.setName("jtfDesProyecto"); // NOI18N
        jtfDesProyecto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfDesProyectoActionPerformed(evt);
            }
        });
        jtfDesProyecto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfDesProyectoKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jpInversionLayout = new javax.swing.GroupLayout(jpInversion);
        jpInversion.setLayout(jpInversionLayout);
        jpInversionLayout.setHorizontalGroup(
            jpInversionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpInversionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jtfCodProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel10)
                .addGap(33, 33, 33)
                .addComponent(jtfDesProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpInversionLayout.setVerticalGroup(
            jpInversionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpInversionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel9)
                .addComponent(jtfCodProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel10)
                .addComponent(jtfDesProyecto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jcbEmpresa.setName("jcbEmpresa"); // NOI18N

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingEmpresa1, eLProperty, jcbEmpresa);
        bindingGroup.addBinding(jComboBoxBinding);

        jcbEmpresa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jcbEmpresaKeyPressed(evt);
            }
        });

        jbtImprimir1.setFont(new java.awt.Font("Arial", 1, 12));
        jbtImprimir1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/document_print.png"))); // NOI18N
        jbtImprimir1.setText("IMPRIMIR");
        jbtImprimir1.setName("jbtImprimir1"); // NOI18N
        jbtImprimir1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtImprimir1ActionPerformed(evt);
            }
        });
        jbtImprimir1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbtImprimir1KeyPressed(evt);
            }
        });

        jCheckBox1.setFont(new java.awt.Font("Arial", 1, 12));
        jCheckBox1.setText("POR ENCARGO");
        jCheckBox1.setName("jCheckBox1"); // NOI18N
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jcbZona.setFont(new java.awt.Font("Arial", 0, 12));
        jcbZona.setName("jcbZona"); // NOI18N

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingZona1, eLProperty, jcbZona);
        bindingGroup.addBinding(jComboBoxBinding);

        jcbZona.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbZonaItemStateChanged(evt);
            }
        });
        jcbZona.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbZonaActionPerformed(evt);
            }
        });
        jcbZona.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jcbZonaKeyPressed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel1.setText("SUCURSAL");
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(209, 209, 209)
                        .addComponent(jbAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jbtImprimir1)
                        .addGap(18, 18, 18)
                        .addComponent(jbCancelar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jchkInversion)
                            .addComponent(jpOperativo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jpInversion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jCheckBox1)
                                .addGap(25, 25, 25)
                                .addComponent(jcbEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(61, 61, 61)
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jcbZona, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jcbEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCheckBox1)
                    .addComponent(jcbZona, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkInversion)
                .addGap(2, 2, 2)
                .addComponent(jpOperativo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(jpInversion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbAceptar)
                    .addComponent(jbtImprimir1)
                    .addComponent(jbCancelar)))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtfCodUnorganicaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfCodUnorganicaActionPerformed

       if (this.jtfCodUnorganica.getText().trim().length() < 1)
            this.jtfDesUnOrganica.requestFocus();
        else
            buscarUnidOrganica();
}//GEN-LAST:event_jtfCodUnorganicaActionPerformed

    private void jtfDesUnOrganicaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfDesUnOrganicaActionPerformed
       
        buscarUnidOrganica();
}//GEN-LAST:event_jtfDesUnOrganicaActionPerformed

    private void jtfDesUnOrganicaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDesUnOrganicaKeyPressed
        
        if (this.jtfCodUnorganica.getText().trim().length() > 0)
            this.jtfCodUnorganica.setText("");
}//GEN-LAST:event_jtfDesUnOrganicaKeyPressed

    private void jtfCodCenCostosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfCodCenCostosActionPerformed
       
        if (this.jtfCodCenCostos.getText().trim().length() < 1)
            this.jtfDescCenCostos.requestFocus();
        else
            buscarCentroCostos();
}//GEN-LAST:event_jtfCodCenCostosActionPerformed

    private void jtfDescCenCostosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfDescCenCostosActionPerformed
        
        buscarCentroCostos();
}//GEN-LAST:event_jtfDescCenCostosActionPerformed

    private void jtfDescCenCostosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDescCenCostosKeyPressed
        
        if (this.jtfCodCenCostos.getText().trim().length() > 0)
            this.jtfCodCenCostos.setText("");
}//GEN-LAST:event_jtfDescCenCostosKeyPressed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
        
        int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de salir?",
      "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
       if(res==javax.swing.JOptionPane.YES_OPTION){

                this.dispose();

         }
    }//GEN-LAST:event_jbCancelarActionPerformed

    
    private void jbAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAceptarActionPerformed

        try{        
            {
                this.evaluarRequerrimiento();
                Utiles_MensajesDialogo.mensajeInfo("Se registro los requerrimientos aprobados!");
                this.limpiar();
                this.requerimientos.clear();
                this.llenaTablaRequerimientos();
            }
        }catch(Exception e){
            Utiles_MensajesDialogo.mensajeError("Error al procesar Requerimientos\n"+e.getMessage());
            e.printStackTrace();
        }
    }//GEN-LAST:event_jbAceptarActionPerformed

    private void jtfCodProyectoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfCodProyectoActionPerformed
       
        if (this.jtfCodProyecto.getText().trim().length() < 1)
            this.jtfDesProyecto.requestFocus();
        else
            buscarProyectos();
    }//GEN-LAST:event_jtfCodProyectoActionPerformed

    private void jtfDesProyectoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfDesProyectoActionPerformed
        
         buscarProyectos();
    }//GEN-LAST:event_jtfDesProyectoActionPerformed

     private void buscarProyectos()
  {
    ProyectoTO proyecto;
    if (this.jtfCodProyecto.getText().trim().length() < 1) {

      try { proyecto = (ProyectoTO)this.intelliHintsProyectos.getSelectedHint();
      } catch (NullPointerException ex) {
        proyecto = null;
      }
    } else {
      proyecto = Listas.getProyectoCodigo(this.jtfCodProyecto.getText().trim());
    }

    if (proyecto == null) {
      Utiles_MensajesDialogo.mensajeError("El proyecto no existe!");
      this.jtfDesProyecto.setText("");
      this.proyecto_pedido = null;
    } else {
      this.jtfDesProyecto.setText(proyecto.toString());
      this.jtfCodProyecto.setText(proyecto.getId_proyecto());
      this.proyecto_pedido = Utiles_Convertir.convertirToProyecto_ProyectoTO(proyecto);
      this.llenaTablaRequerimientos();
    }
  }
    private void jtfDesProyectoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDesProyectoKeyPressed
       
        if (this.jtfCodProyecto.getText().trim().length() > 0)
            this.jtfCodProyecto.setText("");
    }//GEN-LAST:event_jtfDesProyectoKeyPressed

    private void jchkInversionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jchkInversionActionPerformed

        this.limpiar();

    }//GEN-LAST:event_jchkInversionActionPerformed

    private void jtRequerimientosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtRequerimientosKeyPressed


    }//GEN-LAST:event_jtRequerimientosKeyPressed

    private void jbtImprimir1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtImprimir1ActionPerformed

        MiTablePrint pp = new MiTablePrint(this.jtRequerimientos, "REQUERRIMIENTOS", "DETALLE DE REQUERRIMIENTOS APROBADOS");
        pp.showPrintPreview();
}//GEN-LAST:event_jbtImprimir1ActionPerformed

    private void jbtImprimir1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbtImprimir1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jbtImprimir1.doClick();
        }
}//GEN-LAST:event_jbtImprimir1KeyPressed

    private void jcbEmpresaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbEmpresaKeyPressed
       if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            if(this.jcbEmpresa.getSelectedIndex()>=0){
                this.jtfCodUnorganica.requestFocus();
            }
        }
    }//GEN-LAST:event_jcbEmpresaKeyPressed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if(this.jCheckBox1.isSelected()){
            this.jcbEmpresa.setEnabled(true);
        } else{
            this.jcbEmpresa.setEnabled(false);
        }
        this.llenarComboEmpresa();
        this.intelliHintsProyectos.setCompletionList(Listas.obtenerProyectosPorEmpresa(((EmpresaTO)this.jcbEmpresa.getSelectedItem()).getRuc()));
}//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jcbZonaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbZonaItemStateChanged
        this.limpiar();
}//GEN-LAST:event_jcbZonaItemStateChanged

    private void jcbZonaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbZonaActionPerformed

}//GEN-LAST:event_jcbZonaActionPerformed

    private void jcbZonaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcbZonaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER ){
            this.jtfCodUnorganica.requestFocus();
        }
}//GEN-LAST:event_jcbZonaKeyPressed
     
    private List<NecesidadesSumiDetalleTO> obtenerDetallesPorSuministro(List<NecesidadesSumiDetalleTO> completo,String id_suministro){
        List<NecesidadesSumiDetalleTO> parte=new ArrayList(1);
        for(NecesidadesSumiDetalleTO nece:completo){
            if(nece.getId_suministro().trim().equalsIgnoreCase(id_suministro)){
                parte.add(nece);
            }
        }
        return parte;
    }
   private void buscarUnidOrganica()
  {
        List centros_hints;
        UnidadOrganizativaTO unoorg;
        if(this.jtfCodUnorganica.getText().trim().length() < 1)
        {
            unoorg = (UnidadOrganizativaTO)intelliHintsUnidOrganica.getSelectedHint();
            centros_hints = Listas.getCentro_Costos_Unid_Organica(unoorg.getCod_Uni_Organizativa().trim());
        } else
        {
            unoorg = Listas.getUn_organizativa_codigo(jtfCodUnorganica.getText().trim());
            centros_hints = Listas.getCentro_Costos_Unid_Organica(jtfCodUnorganica.getText().trim());
        }
        if(centros_hints.size() < 1)
        {
            Utiles_MensajesDialogo.mensajeError("La unidad organica no existe!");
            this.jtfDesUnOrganica.setText("");
            unid_org_pedido = null;
                try{
                    intelliHintsCentroCostos.getCompletionList().clear();
                    intelliHintsCentroCostos = null;
                }catch(NullPointerException e){

                }

        } else
        {
            unid_org_pedido = Utiles_Convertir.convertirToUnidadOrganizativa_UnidadOrganizativaTO(unoorg);
            jtfDesUnOrganica.setText(unoorg.toString());
            jtfCodUnorganica.setText(unoorg.getCod_Uni_Organizativa());
            if(intelliHintsCentroCostos != null)
            {
                intelliHintsCentroCostos.getCompletionList().clear();
                intelliHintsCentroCostos = null;
                jtfCodCenCostos.setText("");
                this.jtfDescCenCostos.setText("");
            }
            intelliHintsCentroCostos = new ListDataIntelliHints(jtfDescCenCostos, centros_hints);
            jtfCodCenCostos.requestFocus();
        }
  }

   private void buscarCentroCostos()
  {
    CentroCostoTO centro_cost;
    if (this.jtfCodCenCostos.getText().trim().length() < 1) {

      try { centro_cost = (CentroCostoTO)this.intelliHintsCentroCostos.getSelectedHint();
      } catch (NullPointerException ex) {
        centro_cost = null;
      }
    } else {
      centro_cost = Listas.getCentro_Costos_codigo(this.jtfCodCenCostos.getText().trim());
    }

    if (centro_cost == null) {
      Utiles_MensajesDialogo.mensajeError("El centro de costos no existe!");
      this.jtfDescCenCostos.setText("");
      this.centro_costos_pedido = null;
    } else {
      this.jtfDescCenCostos.setText(centro_cost.toString());
      this.jtfCodCenCostos.setText(centro_cost.getCod_CentroCosto());
      this.centro_costos_pedido = Utiles_Convertir.convertirToCentroCosto_CentroCostoTO(centro_cost);
      verificarAprobacionDependencias();
    }
  }

   private void actualizaTablaRequerimientos() {
       
        this.bindingGroup = new BindingGroup();
        this.bindingGroup.addBindingListener(new AbstractBindingListener() {
                       @Override public void synced(Binding binding) {
                        try{
                            if(!requerimientosApro.isEmpty()){
                                int selec=jtRequerimientos.getSelectedRow();
                                NecesidadesSumiTO detaord_aux= requerimientosApro.get(jtRequerimientos.convertRowIndexToModel(selec));
                                if(detaord_aux.getCantAprobado().compareTo(detaord_aux.getCantidad_total())>=0)
                                    detaord_aux.setCantAprobado(detaord_aux.getCantidad_total());
                                actualizaTablaRequerimientos();
                            }

                    }catch(ArrayIndexOutOfBoundsException ex){
                    }
                        catch(Exception e){
                        e.printStackTrace();
                    }

                }
            });

           this.jTableBinding = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ, this.requerimientosApro, this.jtRequerimientos);

            JTableBinding.ColumnBinding columnBinding0 = this.jTableBinding.addColumnBinding(ELProperty.create("${id_suministro}"));

            columnBinding0.setColumnName("ID Suministro");
            columnBinding0.setColumnClass(String.class);
            columnBinding0.setEditable(false);

            JTableBinding.ColumnBinding columnBinding1 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion_suministro}"));

            columnBinding1.setColumnName("Suministro");
            columnBinding1.setColumnClass(String.class);
            columnBinding1.setEditable(false);

            JTableBinding.ColumnBinding columnBinding2 = this.jTableBinding.addColumnBinding(ELProperty.create("${unidad_medida}"));

            columnBinding2.setColumnName("Unid.Medida");
            columnBinding2.setColumnClass(String.class);
            columnBinding2.setEditable(false);

             JTableBinding.ColumnBinding columnBinding3 = this.jTableBinding.addColumnBinding(ELProperty.create("${cantidad_total}"));

            columnBinding3.setColumnName("SUB TOTAL");
            columnBinding3.setColumnClass(BigDecimal.class);
            columnBinding3.setEditable(false);
         
            JTableBinding.ColumnBinding columnBinding4 = this.jTableBinding.addColumnBinding(ELProperty.create("${cantAprobado}"));

            columnBinding4.setColumnName("CANTIDAD APROBADA");
            columnBinding4.setColumnClass(BigDecimal.class);
            columnBinding4.setEditable(true);

            this.bindingGroup.addBinding(this.jTableBinding);
            this.bindingGroup.bind();

            int[] porcentajes= {20,50,10,10,10};
                try {
                    Utiles_Tabla.definirAnchoColumnasJTable(jtRequerimientos, porcentajes);
                     //MiTablePrint.autoSizeTableColumns(this.jtRequerimientos);
                } catch (Exception ex) {
                    Logger.getLogger(jifAdministrarRequerimientos.class.getName()).log(Level.SEVERE, null, ex);
                }

            if(!this.requerimientosApro.isEmpty()){
                this.jbAceptar.setEnabled(true);
            }
    


   }
     public List<NecesidadesSumiTO> convertirDetalleTO(List<NecesidadesSumiTO> requerimientos){
         List<NecesidadesSumiTO> lista= new ArrayList<NecesidadesSumiTO>();
         for(int i=0; i<requerimientos.size(); i++){
             NecesidadesSumiTO nece= requerimientos.get(i);
              nece.setDiferencia(nece.getCantAprobado());
             lista.add(nece);
         }
         return lista;


     }
       public List<NecesidadesSumiTO> convertirDetalleTOInversion(List<NecesidadesSumiTO> requerimientos){

         List<NecesidadesSumiTO> lista= new ArrayList<NecesidadesSumiTO>();
         for(int i=0; i<requerimientos.size(); i++){
             NecesidadesSumiTO nece= requerimientos.get(i);
             nece.setPrecio(BigDecimal.ZERO);
             nece.setMonto(BigDecimal.ZERO);
             nece.setMontoAprobado(BigDecimal.ZERO);
             nece.setDiferencia(nece.getCantAprobado());
             lista.add(nece);
         }
         return lista;
     }
   protected void llenaTablaRequerimientos(){
       Parametros param;
        try {
            param = Listas.getParametrosID("SU1");

            String ano = param.getParam1();
            String mes = param.getParam2();
            boolean estado=false;
            String  emp=empresas.get(this.jcbEmpresa.getSelectedIndex()).getCodigo();
            String zona= ((ZonaTO)this.jcbZona.getSelectedItem()).getId_zona();
                if(this.jchkInversion.isSelected()){
                   this.requerimientos = GestionPedidosDelegate.getInstance().getListaNecesidadesInversionMod(this.proyecto_pedido.getIdProyecto().trim(), ano, emp);
                }else{  
                    this.requerimientos = GestionPedidosDelegate.getInstance().getListaNecesidadesOperativasModZona(this.centro_costos_pedido.getCodCentroCosto().trim(), ano,emp, zona);
                    //this.requerimientos = GestionPedidosDelegate.getInstance().getListaNecesidadesOperativasMod(this.centro_costos_pedido.getCodCentroCosto().trim(), ano, emp);

                }
            if(requerimientos.isEmpty()){
                Utiles_MensajesDialogo.mensajeAlerta("No se ha encontrado requerrimientos");
                this.requerimientos.clear();
                this.actualizaTablaRequerimientos();
                this.limpiar();
            }
            else{
                    if(this.jchkInversion.isSelected()){
                    requerimientosApro=convertirDetalleTOInversion(requerimientos);
                    this.detalleRequerimientos=GestionPedidosDelegate.getInstance().getListaDetalleNecesidadesLocalidadInversion(this.proyecto_pedido.getIdProyecto().trim(), ano, emp);

                    }else{
                    requerimientosApro=convertirDetalleTO(requerimientos);
                    this.detalleRequerimientos=GestionPedidosDelegate.getInstance().getListaDetalleNecesidadesLocalidadOperativo(this.centro_costos_pedido.getCodCentroCosto().trim(), ano, emp);
                    }
                    this.jbAceptar.setEnabled(true);
                    this.bindingGroup = new BindingGroup();
                        this.bindingGroup.addBindingListener(new AbstractBindingListener() {
                           @Override public void synced(Binding binding) {
                            try{
                                if(!requerimientosApro.isEmpty()){
                                    int selec=jtRequerimientos.getSelectedRow();
                                    NecesidadesSumiTO detaord_aux= requerimientosApro.get(jtRequerimientos.convertRowIndexToModel(selec));
                                    if(detaord_aux.getCantAprobado().compareTo(detaord_aux.getCantidad_total())>=0)
                                        detaord_aux.setCantAprobado(detaord_aux.getCantidad_total());
                                        
                                    actualizaTablaRequerimientos();
                                }

                            }catch(ArrayIndexOutOfBoundsException ex){
                            }
                                catch(Exception e){
                                e.printStackTrace();
                            }

                        }
                    });

                    this.jTableBinding = SwingBindings.createJTableBinding(AutoBinding.UpdateStrategy.READ, this.requerimientosApro, this.jtRequerimientos);

                    JTableBinding.ColumnBinding columnBinding0 = this.jTableBinding.addColumnBinding(ELProperty.create("${id_suministro}"));

                    columnBinding0.setColumnName("ID Suministro");
                    columnBinding0.setColumnClass(String.class);
                    columnBinding0.setEditable(false);

                    JTableBinding.ColumnBinding columnBinding1 = this.jTableBinding.addColumnBinding(ELProperty.create("${descripcion_suministro}"));

                    columnBinding1.setColumnName("Suministro");
                    columnBinding1.setColumnClass(String.class);
                    columnBinding1.setEditable(false);

                    JTableBinding.ColumnBinding columnBinding2 = this.jTableBinding.addColumnBinding(ELProperty.create("${unidad_medida}"));

                    columnBinding2.setColumnName("Unid.Medida");
                    columnBinding2.setColumnClass(String.class);
                    columnBinding2.setEditable(false);

                     JTableBinding.ColumnBinding columnBinding3 = this.jTableBinding.addColumnBinding(ELProperty.create("${cantidad_total}"));

                    columnBinding3.setColumnName("SUB TOTAL");
                    columnBinding3.setColumnClass(BigDecimal.class);
                    columnBinding3.setEditable(false);

                    
                    JTableBinding.ColumnBinding columnBinding4 = this.jTableBinding.addColumnBinding(ELProperty.create("${cantAprobado}"));

                    columnBinding4.setColumnName("CANTIDAD APROBADA");
                    columnBinding4.setColumnClass(BigDecimal.class);
                    columnBinding4.setEditable(true);
                    this.bindingGroup.addBinding(this.jTableBinding);
                    this.bindingGroup.bind();

                    }
                int[] porcentajes= {20,50,10,10,10};
                try {
                   Utiles_Tabla.definirAnchoColumnasJTable(this.jtRequerimientos, porcentajes);
                   //MiTablePrint.autoSizeTableColumns(this.jtRequerimientos);
                } catch (Exception ex) {
                    Logger.getLogger(jifAdministrarRequerimientos.class.getName()).log(Level.SEVERE, null, ex);
                }



    } catch (Exception ex) {
           // Utiles_MensajesDialogo.mensajeError("Error al consultar Requerimientos\n"+ex.getMessage());
            return;
        }
   }
    private void limpiar(){
         if(this.jchkInversion.isSelected()){
            this.jpOperativo.setVisible(false);
            this.jpInversion.setVisible(true);
            this.jcbZona.setEnabled(false);
        }else{
            this.jpOperativo.setVisible(true);
            this.jpInversion.setVisible(false);
            this.jcbZona.setEnabled(true);
        }
        this.jtfCodCenCostos.setText("");
        this.jtfCodProyecto.setText("");
        this.jtfCodUnorganica.setText("");
        this.jtfDesProyecto.setText("");
        this.jtfDesUnOrganica.setText("");
        this.jtfDescCenCostos.setText("");
        this.unid_org_pedido=null;
        this.centro_costos_pedido=null;
        this.proyecto_pedido=null;   
        this.requerimientosApro.clear();
        this.tareasRequerimientos.clear();
        this.actualizaTablaRequerimientos();
        this.jbAceptar.setEnabled(false);
        this.pack();
    }
    public void obtenerDatos(){
        int i=0;
         for(NecesidadesSumiTO necesidad: requerimientosApro){
             necesidad.setCantAprobado(new BigDecimal(this.jtRequerimientos.getValueAt(i, 4)+""));
          i++;
         }
    }
    public void evaluarRequerrimiento() throws Exception{
        obtenerDatos();
        List<NecesidadesSumiDetalleTO> general= new ArrayList<NecesidadesSumiDetalleTO>();
        List<NecesidadesSumiTO> generalNecesidades= new ArrayList<NecesidadesSumiTO>();
        for(NecesidadesSumiTO necesidad: requerimientosApro){
            List<NecesidadesSumiDetalleTO> detalle=obtenerSublistaPorSuministro(this.detalleRequerimientos,necesidad.getId_suministro());
                BigDecimal canti;
                BigDecimal porcen;
                BigDecimal suma;
                if(necesidad.getCantidad_total().compareTo(BigDecimal.ZERO)==0){
                 canti=BigDecimal.ZERO;
                 porcen= BigDecimal.ZERO;
               }
               else{
                 canti= necesidad.getCantAprobado();
                 porcen= canti.divide(necesidad.getCantidad_total(), 10, RoundingMode.HALF_EVEN);
               }

                for(NecesidadesSumiDetalleTO detallereque: detalle){
                    suma=BigDecimal.ZERO;
                    detallereque.setSubtotal_aprobado(detallereque.getSubtotal().multiply(porcen));
                    detallereque.setDmes1_aprobado(detallereque.getDmes1().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes1_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes1_aprobado());
                        detallereque.setDmes1_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes1_aprobado());
                    }
                    detallereque.setDmes2_aprobado(detallereque.getDmes2().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes2_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes2_aprobado());
                        detallereque.setDmes2_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes2_aprobado());
                    }
                    detallereque.setDmes3_aprobado(detallereque.getDmes3().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes3_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes3_aprobado());
                        detallereque.setDmes3_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes3_aprobado());
                    }
                    detallereque.setDmes4_aprobado(detallereque.getDmes4().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes4_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes4_aprobado());
                        detallereque.setDmes4_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes4_aprobado());
                    }
                    detallereque.setDmes5_aprobado(detallereque.getDmes5().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes5_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma=suma.subtract(detallereque.getDmes5_aprobado());
                        detallereque.setDmes5_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes5_aprobado());
                    }
                    detallereque.setDmes6_aprobado(detallereque.getDmes6().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes6_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes6_aprobado());
                        detallereque.setDmes6_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes6_aprobado());
                    }
                    detallereque.setDmes7_aprobado(detallereque.getDmes7().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes7_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes7_aprobado());
                        detallereque.setDmes7_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes7_aprobado());
                    }
                    detallereque.setDmes8_aprobado(detallereque.getDmes8().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes8_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes8_aprobado());
                        detallereque.setDmes8_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes8_aprobado());
                    }
                    detallereque.setDmes9_aprobado(detallereque.getDmes9().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes9_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes9_aprobado());
                        detallereque.setDmes9_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes9_aprobado());
                    }
                    detallereque.setDmes10_aprobado(detallereque.getDmes10().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes10_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes10_aprobado());
                        detallereque.setDmes10_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes10_aprobado());
                    }
                    detallereque.setDmes11_aprobado(detallereque.getDmes11().multiply(porcen).setScale(2,RoundingMode.HALF_UP));
                    suma=suma.add( detallereque.getDmes11_aprobado());
                    if(suma.compareTo(detallereque.getSubtotal_aprobado())>0){
                        suma=suma.subtract(detallereque.getDmes11_aprobado());
                        detallereque.setDmes11_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                        suma=suma.add(detallereque.getDmes11_aprobado());
                    }

                    detallereque.setDmes12_aprobado((detallereque.getSubtotal_aprobado().subtract(suma)));
                    detallereque.setMonto_aprobado(detallereque.getSubtotal_aprobado().multiply(detallereque.getPrecio()));
                    general.add(detallereque);
                }
                necesidad.setCantAprobado(canti);
                generalNecesidades.add(necesidad);

        }

        GestionPedidosDelegate.getInstance().aprobarRequerrimientos( Propiedades.getUsuario(),   Propiedades.getMac(), general, generalNecesidades);
    }
     List<NecesidadesSumiDetalleTO> obtenerSublistaPorSuministro(List<NecesidadesSumiDetalleTO> lista,String id_sumi) throws Exception{
        List<NecesidadesSumiDetalleTO> retorno=new ArrayList(1);
        String zona= ((ZonaTO)this.jcbZona.getSelectedItem()).getId_zona();
        for(NecesidadesSumiDetalleTO deta:lista){
            if(deta.getId_suministro().trim().compareToIgnoreCase(id_sumi)==0 && deta.getId_zona().trim().compareTo(zona)==0){
                retorno.add(deta);
              
            }
        }
        return retorno;

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private administracion.BeanBinding.CboBeanBindingEmpresa cboBeanBindingEmpresa1;
    private administracion.BeanBinding.CboBeanBindingZona cboBeanBindingZona1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbAceptar;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbtImprimir1;
    private javax.swing.JComboBox jcbEmpresa;
    private javax.swing.JComboBox jcbZona;
    private javax.swing.JCheckBox jchkInversion;
    private javax.swing.JPanel jpInversion;
    private javax.swing.JPanel jpOperativo;
    private javax.swing.JTable jtRequerimientos;
    private javax.swing.JTextField jtfCodCenCostos;
    private javax.swing.JTextField jtfCodProyecto;
    private javax.swing.JTextField jtfCodUnorganica;
    private javax.swing.JTextField jtfDesProyecto;
    private javax.swing.JTextField jtfDesUnOrganica;
    private javax.swing.JTextField jtfDescCenCostos;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

}
